﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Configuration.Assemblies;
using System.Configuration;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace working
{
    public static class Util
    {
        private static string workDir;
        private static OpenFileDialog openFileDialog;
        private static SaveFileDialog saveFileDialog;
        private static FolderSelectDialog folderDialog;
        public static void Init()
        {
            workDir = Application.StartupPath + "\\data";

            if (!Directory.Exists(workDir))
            {
                System.IO.Directory.CreateDirectory(workDir);
            }
            openFileDialog = new OpenFileDialog();
            saveFileDialog = new SaveFileDialog();
            folderDialog = new FolderSelectDialog();
        }

        public static string GetBranchFolder(string branch)
        {
            var path = workDir + "\\" + branch;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

        public static string GetConfigFromFolder(string folder)
        {
            var path = folder + "\\config.json";
            return path;
        }
        public static string GetConfigResourceFolder(string id)
        {
            return GetChildFolder(id, "_resource");
        }
        public static string GetConfigTableFolder(string id)
        {
            return GetChildFolder(id, "_table");
        }
        public static string GetConfigDocFolder(string id)
        {
            return GetChildFolder(id, "_doc");
        }
        
        public static string GetBackupFolder(string id)
        {
            return GetChildFolder(id,"_backup");
        }

        private static string GetChildFolder(string id,string folderName)
        {
            var folder = GetBranchFolder(id);
            var path = folder + "\\" + folderName;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

        public static string GetRoot()
        {
            return workDir;
        }

        public static string OpenFileSelect(string title,string folder,string filter= "AllFile *.*|*.*")
        {
            openFileDialog.Title = title;
            openFileDialog.InitialDirectory = folder;
            openFileDialog.Filter = filter;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                return openFileDialog.FileName;
            }
            return null;
        }

        public static string SaveFileSelect(string title, string folder, string filter = "AllFile *.*|*.*")
        {
            saveFileDialog.Title = title;
            saveFileDialog.Filter = filter;
            saveFileDialog.InitialDirectory = folder;
            if(saveFileDialog.ShowDialog( ) == DialogResult.OK)
            {
                return saveFileDialog.FileName;
            }
            return null;
        }

        public static string OpenFolderDialog(string title,string folder)
        {
            folderDialog.Title = title;
            folderDialog.InitialDirectory = folder;
            if(folderDialog.ShowDialog())
            {
                return folderDialog.FileName;
            }
            return null;
        }

        public static System.Diagnostics.Process OpenFolder(string path)
        {
            if (!System.IO.Directory.Exists(path)) path = "C:/";
           return System.Diagnostics.Process.Start(path,"/e");
        }
        /// <summary>
        /// 源文件夹中的对象拷贝到目标文件夹
        /// </summary>
        /// <param name="oringalFolder"></param>
        /// <param name="folder"></param>
        public static void CopyFilesTo(string oringalFolder, string folder)
        {
            if (!System.IO.Directory.Exists(folder)){
                System.IO.Directory.CreateDirectory(folder);
            }
            List<string> childs = new List<string>();
            var files = System.IO.Directory.GetFiles(oringalFolder);
            var dirs = System.IO.Directory.GetDirectories(oringalFolder);
            childs.AddRange(files);
            childs.AddRange(dirs);
            if (childs.Count > 0)
            {
                string oringal_files = string.Join("\0", childs.ToArray()) + "\0\0";
                FileEx.Copy(oringal_files, folder + "\0\0");
            }
        }
        /// <summary>
        /// 目标路径和原始路径文件夹名一样，也有可能是文件
        /// </summary>
        /// <param name="srcPath"></param>
        /// <param name="targetPath"></param>
        /// <param name="propmt"></param>
        public static void Copy(string srcPath, string targetPath,bool propmt = true)
        {
            if (!System.IO.Directory.Exists(srcPath) && !System.IO.File.Exists(srcPath)) return;
            if (string.IsNullOrEmpty(targetPath)) return;

            var folder = System.IO.Path.GetDirectoryName(targetPath);

            if (!System.IO.Directory.Exists(folder)){
                System.IO.Directory.CreateDirectory(folder);
            }

            FileEx.Copy(srcPath + "\0\0", folder + "\0\0", propmt);
        }
        public static void CopyDir(string srcPath, string targetPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加
                if (targetPath[targetPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    targetPath += System.IO.Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建
                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles（srcPath）；
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (System.IO.Directory.Exists(file))
                    {
                        CopyDir(file, targetPath + System.IO.Path.GetFileName(file));
                    }
                    // 否则直接Copy文件
                    else
                    {
                        System.IO.File.Copy(file, targetPath + System.IO.Path.GetFileName(file), true);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static void CopyFile(string currentPath, string targetPath)
        {
            if(System.IO.File.Exists(currentPath))
            {
                var dir = System.IO.Path.GetDirectoryName(targetPath);
                if (!System.IO.Directory.Exists(dir)){
                    System.IO.Directory.CreateDirectory(dir);
                }
                System.IO.File.Copy(currentPath, targetPath,true);
            }
        }
        /// <summary>
        /// 打开文件夹并选中文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void OpenFolderAndSelectFile(string fileName)
        {
            if (!System.IO.File.Exists(fileName)) return;

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
            psi.Arguments = " /select," + System.IO.Path.GetFullPath(fileName);
            System.Diagnostics.Process.Start(psi);
        }

        public static void OpenSelectFolder(string folder)
        {
            if (!System.IO.Directory.Exists(folder)) return;

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
            psi.Arguments = " /e,/root," + System.IO.Path.GetFullPath(folder);
            System.Diagnostics.Process.Start(psi);
        }

        public static bool ExistConfigItem(string keyName)
        {
            Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //判断配置文件中是否存在键为keyName的项
            foreach (var key in config.AppSettings.Settings.AllKeys)
            {
                if (key == keyName)
                {
                    //存在
                    return true;
                }
            }
            return false;
        }
        public static string GetConfigItem(string keyName)
        {
            Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            return config.AppSettings.Settings[keyName].Value;
        }
        public static void SetConfigItem(string keyName, string newKeyValue)
        {
            Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (ExistConfigItem(keyName))
            {
                config.AppSettings.Settings[keyName].Value = newKeyValue;
            }
            else
            {
                config.AppSettings.Settings.Add(keyName, newKeyValue);
            }
            config.Save(ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }

        public static string ToB64String<T>(T obj)
        {
           var json = JsonConvert.SerializeObject(obj);
            var bytes = System.Text.Encoding.UTF8.GetBytes(json);
            var b46 = Convert.ToBase64String(bytes);
            return b46;
        }

        public static T FromB64String<T>(string str)
        {
            var bytes = Convert.FromBase64String(str);
            var json = System.Text.Encoding.UTF8.GetString(bytes);
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}
